/*
 * @Author: jhy
 * @Date: 2024-07-16 19:28:31
 * @LastEditTime: 2024-08-15 19:22:08
 * @LastEditors: jhy
 * @Description: 
 * @FilePath: /other/next-admin/src/app/[locale]/api/upload/route.ts
 */
import { writeFile } from "fs/promises";
import { NextResponse } from "next/server";
import path from "path";

export const POST = async (req, res) => {
    // console.log('req:', req);
    // console.log('req.url:', req.url);
    // console.log('req.headers:', req.headers.values());
    // console.log('req.headers string:', req.headers.get('host'));
    // console.log('req.headers origin:', req.headers.get('origin'));
    // console.log('req.query:', req.query);
    // console.log('req.body:', req.body);
    // console.log('res:', res);
    const formData = await req.formData();
    const file = formData.get("file");

    if (!file) {
        return NextResponse.json({ error: "No files received." }, { status: 400 }); 
    }

    const buffer = Buffer.from(await file.arrayBuffer());
    const filename = Date.now() + file.name.replaceAll(" ", "_");
    //   console.log(formData,file,'dddddddddddddddddddddddddd')

    try {
        await writeFile(
            path.join(process.cwd(), "public/uploads/news/" + filename),
            buffer
        );
        let origin = req.headers.get('origin');
        return NextResponse.json({ Message: "Success", status: 200, data:{ url: origin + "/uploads/news/" + filename } });
    } catch (error) {
        console.log("Error occured ", error);
        return NextResponse.json({ Message: "Failed", status: 500 });
    }
};